import Vue from 'vue'
import VueRouter from 'vue-router'

import { Message } from 'element-ui'

var originalPush = VueRouter.prototype.push
var originalReplace = VueRouter.prototype.replace

// push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

// 空页面，废弃页面以及公共页面
import noDataPage from './noDataPage'
//人员 在职、离职、档案
import employee from './employee'
// 项目管理/宜昌项目去重
import project from './project'
// 工资代发
import salary from './salary'
// 政务考核
import assessment from './assessment'
// 信用评价
import creditRating from './creditRating'
// 帮助中心
import helpCenter from './helpCenter'
// 首页,大屏
import home from './home'
//工伤保险
import insurance from './insurance'
//保证金
import margin from './margin'
// 通知中心
import noticeCenter from './noticeCenter'
// 违法事件维权纠纷
import rightsProtection from './rightsProtection'
// 分账管理 专户、拨付设置
import separateAccount from './separateAccount'
// 系统设置
import systemSettings from './systemSettings'
// 预警中心
import warningCenter from './warningCenter'
// 实名管理
import realName from './realName'
// 银行端页面
import bank from './bank'
// 企业管理
import enterprise from './enterprise'
// 统计报表
import statisticalReport from './statisticalReport'
// 统计
import statistics from './statistics'
// 企业欠薪诉求
import defectsCase from './defectsCase'
// 登录之前的页面
import login from './login'
// 滁州招商局
import otherSystem from './otherSystem'
// 报表3期 20201224
import statement from './statement'
// 在线执法
import onlineLaw from './onlineLaw'

import store from './../store'
// 巡查
import patrol from './patrol'
// 滁州网络网格管理
import networkgrid from './networkgrid'
// 鹤峰需求
import oneCode from './oneCode'
//项目标签化管理
import labelManagement from './labelManagement'
// 接口平台
import interfacePlatform from './interfacePlatform'
//银行数据统计
import bankStatistics from './bankStatistics'
// 项目包保
import projectWarranty from './projectWarranty'
//夷陵大屏
import yilingBigScreen from './ylBigScreen'
// 鄂州市梁子湖区-指挥中心
import eZhouBigScreen from './eZhouBigScreen'
// 黄石招标局
import dataDocking from './dataDocking'
// 昆明案件导入
import kMCaseComplaint from './kMCaseComplaint'
// 八大员配置
import eightMembersConfig from './eightMembersConfig'
//务工人员评价记录
import worker from './worker'
// 保险
import newInsurance from './newInsurance'
//住建数据上传
import zhujianData from './zhujianData'
// 网格中心巡查
import gridPatrol from './gridPatrol'
//黄石大冶红黑榜设置
import redBlackList from './redBlackList'
//黄石大冶问题答疑
import answerQuestion from './answerQuestion'

const routes = [
  ...login,
  {
    path: '/home',
    redirect: {
      name: 'home',
    },
    component: () => import('@/components/container'),
    children: [
      {
        path: '/home',
        redirect: (to) => {
          var urlName = localStorage.getItem('urlName')
          return {
            name: urlName,
          }
        },
        name: 'home',
        component: () => import('@/components/home'),
      },
      ...home,
      ...employee,
      ...noDataPage,
      ...project,
      ...salary,
      ...assessment,
      ...creditRating,
      ...helpCenter,
      ...insurance,
      ...margin,
      ...noticeCenter,
      ...rightsProtection,
      ...separateAccount,
      ...systemSettings,
      ...warningCenter,
      ...realName,
      ...bank,
      ...enterprise,
      ...statisticalReport,
      ...statistics,
      ...otherSystem,
      ...defectsCase,
      ...statement,
      ...patrol,
      ...networkgrid,
      ...onlineLaw,
      ...oneCode,
      ...labelManagement,
      ...interfacePlatform,
      ...bankStatistics,
      ...projectWarranty,
      ...yilingBigScreen,
      ...eZhouBigScreen,
      ...dataDocking,
      ...kMCaseComplaint,
      ...eightMembersConfig,
      ...worker,
      ...newInsurance,
      ...zhujianData,
      ...gridPatrol,
      ...redBlackList,
      ...answerQuestion,
    ],
  },
]

const router = new VueRouter({
  routes,
})

// 登录拦截
router.beforeEach((to, from, next) => {
  //如果是重新登录，请求 区域、行业、投资类型、开工状态字典
  if (from.path === '/login/loginNext' || '/login/loginNextCz') {
    store.dispatch('getInvestmenttype', {})
    store.dispatch('getStatus', {})
    store.dispatch('getIndustry', {})
    store.dispatch('getAreas', { areaId: store.state.areaInfoArr.areaId })
    store.dispatch('getIndustryNC', {})
  }
  if (to.matched.length === 0) {
    next('/home/plaseWait') //目标路由匹配失败，跳转404页面，避免空白页面
  } else {
    if (
      to.path === '/login/loginFirst' ||
      to.path === '/login/loginNext' ||
      to.path === '/login/loginNextCz' ||
      to.path === '/register/register' ||
      to.path === '/register/registerNext' ||
      to.path === '/findPassword/findPassword' ||
      to.path === '/common/creditPublicity' ||
      to.path === '/common/complaintPublicity' ||
      to.path === '/common/policyAnnunciate' ||
      to.path === '/common/policyAnnunciateDetail' ||
      to.path === '/common/routineProblem' ||
      to.path === '/common/complaintPublicityYS' ||
      to.path === '/common/registration' ||
      to.path === '/common/creditCommitment' ||
      to.path === '/register/registerInterfaceAccount' ||
      to.path === '/register/registerNextInterfaceAccount' ||
      to.path === '/findPassword/findPasswordInterface' ||
      to.path === '/common/newCreditPublicity'
      // || to.path === '/zhujianData/zjEnterpriseInfo'
    ) {
      next()
    } else {
      localStorage.setItem('toFullPath', to.fullPath)
      let token = localStorage.getItem('access_token')
      if (!token) {
        next('/login/loginFirst')
      } else {
        next()
      }
    }
  }
})

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  var ch = '/'
  var pathname = window.location.pathname
  pathname = pathname.replace(new RegExp(ch, 'g'), '')

  // const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    //console.log(targetPath)
    Message.closeAll()
    Message({
      type: 'warning ',
      message: '检测到服务器存在更新,请F5刷新页面! ',
      duration: 3000,
    })
    setTimeout(() => {
      window.location.href =
        window.location.protocol +
        '//' +
        window.location.host +
        '/' +
        pathname +
        '/#/'
    }, 3000)
    //router.replace(targetPath);
  }
})

export default router
